<template>
  <div class="app-container" v-loading="xsLoading">
    <h2 style="text-align: center">字体和七步法</h2>

    <el-steps
      :active="2"
      process-status="wait"
      align-center
      style="margin-bottom: 40px"
    >
      <el-step title="添加字体" />
      <el-step title="添加七步" />
    </el-steps>
    <div>
      <el-form :inline="true">
        <el-form-item>
          <el-select
            v-model="buzhou"
            placeholder="请选择类型"
            @change="buzhouChange"
          >
            <el-option label="欣赏" :value="0"> </el-option>
            <el-option label="认读" :value="1"> </el-option>
            <el-option label="观察" :value="2"> </el-option>
            <el-option label="分析" :value="4"> </el-option>
            <el-option label="笔法" :value="3"> </el-option>
            <el-option label="视频" :value="7"> </el-option>
            <el-option label="对比" :value="5"> </el-option>
            <el-option label="随堂练习" :value="6"> </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="addAppreciation(0)">新增</el-button>
        </el-form-item>
      </el-form>
    </div>
    <el-table :data="xsList" stripe v-loading="xsLoading" style="width: 100%">
      <el-table-column type="expand">
        <template slot-scope="props">
          <el-table :data="props.row.children" stripe style="width: 100%">
            <el-table-column
              prop="id"
              header-align="center"
              align="center"
              label="欣赏图片id"
            >
            </el-table-column>
            <el-table-column
              prop="appreciationPicture"
              header-align="center"
              align="center"
              label="欣赏图片"
            >
            <template slot-scope="scope">
              <el-image :src="scope.row.appreciationPicture"></el-image>
            </template>
            </el-table-column>
            <el-table-column
              prop="porder"
              header-align="center"
              align="center"
              label="顺序"
            ></el-table-column>
            <el-table-column header-align="center" align="center" label="操作">
              <template slot-scope="scope">
                <el-button
                  type="text"
                  @click="addAppreciationPicture(1, scope.row.id)"
                  >修改</el-button
                >
                <el-button
                  type="text"
                  @click="deleteById2(scope.row.id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </template>
      </el-table-column>
      <el-table-column
        prop="id"
        header-align="center"
        align="center"
        label="欣赏id"
      ></el-table-column>
      <el-table-column
        prop="typefaceName"
        header-align="center"
        align="center"
        label="字体名称"
      ></el-table-column>
      <el-table-column header-align="center" align="center" label="操作">
        <template slot-scope="scope">
          <el-button
            type="text"
            @click="addAppreciationPicture(0, scope.row.id)"
            >添加图片</el-button
          >
          <el-button
            style=""
            type="text"
            @click="addAppreciation(1, scope.row.id)"
            >修改</el-button
          >
          <el-button type="text" @click="deleteById(scope.row.id)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <!-- <ul class="chanpterList">
      <li v-for="xs in xsList" :key="xs.id">
        <p>
          {{ xs.typefaceName }}

          <span class="acts">
            <el-button type="text" @click="addAppreciationPicture(0, xs.id)"
              >添加图片</el-button
            >
            <el-button style="" type="text" @click="addAppreciation(1, xs.id)"
              >修改</el-button
            >
            <el-button type="text" @click="deleteById(xs.id)">删除</el-button>
          </span>
        </p>

        <ul class="chanpterList videoList">
          <li
            v-for="appreciationPicture in xs.children"
            :key="appreciationPicture.id"
          >
            <p>
              欣赏图片
              <span class="acts">
                <el-button
                  type="text"
                  @click="addAppreciationPicture(1, appreciationPicture.id)"
                  >修改</el-button
                >
                <el-button
                  type="text"
                  @click="deleteById2(appreciationPicture.id)"
                  >删除</el-button
                >
              </span>
            </p>
          </li>
        </ul>
      </li>
    </ul> -->
    <el-dialog
      :visible.sync="dialogAppreciationVisible"
      :title="type == 0 ? '添加欣赏信息' : '修改欣赏信息'"
    >
      <el-form
        :rules="dataRule"
        ref="appreciationForm"
        :model="appreciation"
        label-width="120px"
      >
        <el-form-item label="名称" prop="typefaceName" style="width: 300px">
          <el-input v-model="appreciation.typefaceName" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogAppreciationVisible = false">取 消</el-button>
        <el-button
          :disabled="saveAppreciationBtnDisabled"
          type="primary"
          @click="saveOrUpdate"
          >确 定</el-button
        >
      </div>
    </el-dialog>
    <el-dialog
      :visible.sync="dialogAppreciationPictureVisible"
      :title="type == 0 ? '添加欣赏图片信息' : '修改欣赏图片信息'"
    >
      <el-form
        :rules="dataRule1"
        ref="appreciationPictureForm"
        :model="appreciationPicture"
        label-width="120px"
      >
        <el-form-item label="图片" prop="appreciationPicture">
          <el-upload
            class="avatar-uploader"
            :action="'http://121.41.167.195:8000/api/oss/upload'"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img
              v-if="appreciationPicture.appreciationPicture"
              :src="appreciationPicture.appreciationPicture"
              class="avatar"
            />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="顺序" prop="porder">
          <el-input-number
            v-model="appreciationPicture.porder"
            controls-position="right"
            :min="1"
          ></el-input-number>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogAppreciationPictureVisible = false"
          >取 消</el-button
        >
        <el-button
          :disabled="saveAppreciationPictureBtnDisabled"
          type="primary"
          @click="saveOrUpdate1"
          >确 定</el-button
        >
      </div>
    </el-dialog>

    <div>
      <el-button @click="previous">上一步</el-button>
      <!-- <el-button :disabled="saveBtnDisabled" type="primary" @click="next"
        >完成</el-button
      > -->
    </div>
  </div>
</template>

<script>
import Vue from "vue";
export default {
  data() {
    return {
      buzhou: 0,
      xsLoading: false,
      saveBtnDisabled: false, // 保存按钮是否禁用
      appreciation: {
        // 出版社对象
        typefaceName: "",
        tid: null,
        id: null,
      },
      xsList: [],
      appreciationPicture: {
        id: null,
        appreciationPicture: "",
        porder: 1,
        pid: null,
      },
      type: 0, // 0:添加1:修改
      xzBtn: false,
      dialogAppreciationVisible: false,
      saveAppreciationBtnDisabled: false,
      dialogAppreciationPictureVisible: false,
      saveAppreciationPictureBtnDisabled: false,
      dataRule: {
        typefaceName: [
          { required: true, message: "名称不能为空", trigger: "blur" },
        ],
      },
      dataRule1: {
        porder: [{ required: true, message: "顺序不能为空", trigger: "blur" }],
        appreciationPicture: [{ required: true, message: "图片不能为空" }],
      },
    };
  },

  activated() {
    this.buzhou = 0;
    // 传的就是wordId
    this.appreciation.tid = this.$route.params.id;
    // 有数据就要回显数据
    this.getAppreciationByWordId();
  },

  methods: {
    buzhouChange(value) {
      switch (value) {
        case 0:
          // 欣赏
          this.$router.push({
            path: "/ruanbi/ruanbixsAdd/" + this.$route.params.id,
          });
          break;
        case 1:
          // 认读
          this.$router.push({
            path: "/ruanbi/ruanbirdAdd/" + this.$route.params.id,
          });
          break;
        case 2:
          // 观察
          this.$router.push({
            path: "/ruanbi/ruanbigcAdd/" + this.$route.params.id,
          });
          break;
        case 3:
          // 笔法
          this.$router.push({
            path: "/ruanbi/ruanbibfAdd/" + this.$route.params.id,
          });
          break;
        case 4:
          // 分析
          this.$router.push({
            path: "/ruanbi/ruanbifxAdd/" + this.$route.params.id,
          });
          break;
        case 5:
          // 对比
          this.$router.push({
            path: "/ruanbi/ruanbidbAdd/" + this.$route.params.id,
          });
          break;
        case 6:
          // 随堂练习
          this.$router.push({
            path: "/ruanbi/ruanbistlxAdd/" + this.$route.params.id,
          });
          break;
        default:
          // 视频
          this.$router.push({
            path: "/ruanbi/wordVideo/" + this.$route.params.id,
          });
          break;
      }
    },
    //上传成功后的回调函数
    handleAvatarSuccess(response) {
      this.appreciationPicture.appreciationPicture = response.url;
    },
    beforeAvatarUpload() {},
    // 文件上传
    submitUpload() {
      let { uploadFiles, action, data } = this.$refs.uploadFile;
      this.uploadFiles({
        uploadFiles,
        data,
        action,
        success: (response) => {
          console.log(response);
          // 上传成功后，将里面的内容删除
          this.$refs.uploadFile.clearFiles();
        },
        error: (error) => {
          console.log("失败了", error);
        },
      });
    },
    uploadFiles({ uploadFiles, headers, data, action, success, error }) {
      let form = new FormData();
      // 文件对象
      uploadFiles.map((file) => form.append("filedatas", file.raw));
      // 附件参数
      for (let key in data) {
        form.append(key, data[key]);
      }
      let xhr = new XMLHttpRequest();
      // 异步请求
      xhr.open("post", action, true);
      // 设置请求头
      xhr.setRequestHeader("Authorization", this.$cookie.get("token"));
      xhr.onreadystatechange = function () {
        if (xhr.readyState == 4) {
          if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304) {
            success && success(JSON.parse(xhr.responseText)); // 转为json
          } else {
            error && error(xhr.status);
          }
        }
      };
      xhr.send(form);
    },
    handleChange(file, fileList) {
      this.fileList = fileList;
      console.log(this.fileList);
    },
    handleSuccess(response, file, fileList) {
      this.srcList.push(response.url);
    },
    handleRemove(file, fileList) {
      this.fileList = fileList;
      console.log(this.fileList);
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    getAppreciationByWordId() {
      this.xsLoading = true;
      this.$http({
        url: this.$http.adornUrl(
          `/sf/cbappreciation/getAppreciationByWordId/${this.appreciation.tid}`
        ),
        method: "get",
      }).then(({ data }) => {
        this.xsList = [];
        this.xzBtn = false;
        if (data && data.code === 0) {
          
          if (data.xsList != null && data.xsList.length > 0) {
            this.xsList = data.xsList;
            this.xzBtn = true;
          }
        } else {
          // this.appreciation = { typefaceName: "", editionCover: "", id: null };
        }
        this.xsLoading = false;
      });
    },
    // 章节对话框中的保存或修改
    saveOrUpdate() {
      if (this.type == 0) {
        // 添加章节
        this.appreciationFormSubmit();
      } else {
        // 修改章节
        this.updateAppreciation();
      }
    },
    // 更新章节图片信息
    updateAppreciation() {
      this.$refs["appreciationForm"].validate((valid) => {
        if (valid) {
          this.$http({
            url: this.$http.adornUrl(`/sf/cbappreciation/update`),
            method: "post",
            data: this.$http.adornData(
              {
                id: this.appreciation.id,
                tid: this.appreciation.cid,
                typefaceName: this.appreciation.typefaceName,
              },
              false
            ),
          }).then(({ data }) => {
            if (data && data.code === 0) {
              this.$message({
                message: "修改成功",
                type: "success",
                duration: 1500,
                onClose: () => {
                  this.getAppreciationByWordId();
                  this.dialogAppreciationVisible = false;
                },
              });
            } else {
              this.$message.error(data.msg);
            }
          });
        }
      });
    },
    // 更新章节图片信息
    updateAppreciationPicture() {
      this.$refs["appreciationPictureForm"].validate((valid) => {
        if (valid) {
          this.$http({
            url: this.$http.adornUrl(`/sf/cbappreciationpicture/update`),
            method: "post",
            data: this.$http.adornData(
              {
                id: this.appreciationPicture.id,
                tid: this.appreciationPicture.tid,
                porder: this.appreciationPicture.porder,
                appreciationPicture: this.appreciationPicture
                  .appreciationPicture,
              },
              false
            ),
          }).then(({ data }) => {
            if (data && data.code === 0) {
              this.$message({
                message: "修改成功",
                type: "success",
                duration: 1500,
                onClose: () => {
                  this.getAppreciationByWordId();
                  this.dialogAppreciationPictureVisible = false;
                },
              });
            } else {
              this.$message.error(data.msg);
            }
          });
        }
      });
    },
    // 章节图片对话框中的保存或修改
    saveOrUpdate1() {
      if (this.type == 0) {
        // 添加章节
        this.appreciationPictureFormSubmit();
      } else {
        // 修改章节
        this.updateAppreciationPicture();
      }
    },
    // 打开对话框，添加、修改
    addAppreciation(status, id) {
      // 重置表单 应该只是把表单有的清空而已
      this.$nextTick(() => {
        this.$refs.appreciationForm.resetFields();
      });
      if (status == 0) {
        // 添加
        this.type = 0;
        // 清空
        this.appreciation.id = null;
      } else {
        // 修改
        this.type = 1;
        // 回显数据
        this.$http({
          url: this.$http.adornUrl("/sf/cbappreciation/info/" + id),
          method: "get",
        }).then(({ data }) => {
          this.appreciation.id = data.cbAppreciation.id;
          this.appreciation.typefaceName = data.cbAppreciation.typefaceName;
          this.appreciation.tid = data.cbAppreciation.tid;
        });
      }
      this.dialogAppreciationVisible = true;
    },
    // 打开对话框，添加、修改
    addAppreciationPicture(status, id) {
      // 重置表单 应该只是把表单有的清空而已
      this.$nextTick(() => {
        this.$refs.appreciationPictureForm.resetFields();
      });
      if (status == 0) {
        // 添加
        this.type = 0;
        // 清空
        this.appreciationPicture.id = null;
        this.appreciationPicture.pid = id;
        this.appreciationPicture.appreciationPicture = "";
      } else {
        // 修改
        this.type = 1;
        // 回显数据
        this.$http({
          url: this.$http.adornUrl("/sf/cbappreciationpicture/info/" + id),
          method: "get",
        }).then(({ data }) => {
          this.appreciationPicture.id = data.cbAppreciationPicture.id;
          this.appreciationPicture.appreciationPicture =
            data.cbAppreciationPicture.appreciationPicture;
          this.appreciationPicture.porder = data.cbAppreciationPicture.porder;
          this.appreciationPicture.pid = data.cbAppreciationPicture.pid;
        });
      }
      this.dialogAppreciationPictureVisible = true;
    },
    // 表单提交
    appreciationFormSubmit() {
      // 表单验证
      this.$refs["appreciationForm"].validate((valid) => {
        if (valid) {
          this.$http({
            url: this.$http.adornUrl(`/sf/cbappreciation/save1`),
            method: "post",
            data: this.$http.adornData(
              {
                typefaceName: this.appreciation.typefaceName,
                tid: this.appreciation.tid,
                //srcList: this.srcList,
              },
              false
            ),
          }).then(({ data }) => {
            if (data && data.code === 0) {
              this.$message({
                message: "添加成功",
                type: "success",
                duration: 1500,
                onClose: () => {
                  // 刷新
                  this.getAppreciationByWordId();
                  // 只能添加一次
                  this.xzBtn = true;
                  this.dialogAppreciationVisible = false;
                },
              });
            } else {
              this.$message.error(data.msg);
            }
          });
        }
      });
    },
    // 表单提交
    appreciationPictureFormSubmit() {
      // 表单验证
      this.$refs["appreciationPictureForm"].validate((valid) => {
        if (valid) {
          this.$http({
            url: this.$http.adornUrl(`/sf/cbappreciationpicture/save`),
            method: "post",
            data: this.$http.adornData(
              {
                pid: this.appreciationPicture.pid,
                porder: this.appreciationPicture.porder,
                appreciationPicture: this.appreciationPicture
                  .appreciationPicture,
                //srcList: this.srcList,
              },
              false
            ),
          }).then(({ data }) => {
            if (data && data.code === 0) {
              this.$message({
                message: "添加成功",
                type: "success",
                duration: 1500,
                onClose: () => {
                  // 刷新
                  this.getAppreciationByWordId();
                  // 只能添加一次
                  this.xzBtn = true;
                  this.dialogAppreciationPictureVisible = false;
                },
              });
            } else {
              this.$message.error(data.msg);
            }
          });
        }
      });
    },
    // 通过章节id删除章节
    deleteById(id) {
      this.$confirm(`确定对[欣赏id=${id}]进行[删除]操作?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$http({
            url: this.$http.adornUrl("/sf/cbappreciation/delete"),
            method: "post",
            data: this.$http.adornData([id], false),
          }).then(({ data }) => {
            if (data && data.code === 0) {
              this.$message({
                message: "删除成功",
                type: "success",
                duration: 1500,
                onClose: () => {
                  this.getAppreciationByWordId();
                },
              });
            } else {
              this.$message.error(data.msg);
            }
          });
        })
        .catch(() => {});
    },
    // 通过章节id删除章节
    deleteById2(id) {
      this.$confirm(`确定对[欣赏图片id=${id}]进行[删除]操作?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$http({
            url: this.$http.adornUrl("/sf/cbappreciationpicture/delete"),
            method: "post",
            data: this.$http.adornData([id], false),
          }).then(({ data }) => {
            if (data && data.code === 0) {
              this.$message({
                message: "删除成功",
                type: "success",
                duration: 1500,
                onClose: () => {
                  this.getAppreciationByWordId();
                },
              });
            } else {
              this.$message.error(data.msg);
            }
          });
        })
        .catch(() => {});
    },
    // 上一步
    previous() {
      this.$router.push({
        path: "/ruanbi/word7",
      });
    },
    next() {
      this.$router.push({
        path: "/ruanbi/ruanbiInfo",
      });
    },
  },
};
</script>
<style scoped>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.chanpterList {
  position: relative;
  list-style: none;
  margin: 0;
  padding: 0;
}
.chanpterList li {
  position: relative;
}
.chanpterList p {
  float: left;
  font-size: 20px;
  margin: 10px 0;
  padding: 10px;
  height: 70px;
  line-height: 50px;
  width: 100%;
  border: 1px solid #ddd;
}
.chanpterList .acts {
  float: right;
  font-size: 14px;
}

.videoList {
  padding-left: 50px;
}
.videoList p {
  float: left;
  font-size: 14px;
  margin: 10px 0;
  padding: 10px;
  height: 50px;
  line-height: 30px;
  width: 100%;
  border: 1px dotted #ddd;
}
</style>
